<?php
namespace app\Index\Controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use think\captcha\Captcha;
class Login extends Controller
{

    //渲染输出登陆界面
    public function index()
    {


        return view('login/index', [
            'title' => '登录页面',

        ]);
    }
    // 用户登录验证
    public function login()
    {


        //接收用户名和密码

        $username = $_POST['user'];
        $password = $_POST['pass'];

        //验证

        $data = Db::name('index_login')->field('user, pass,id')->where(array('user' => $username))->find();


        if (!$data) {
            $this->error('用户名不存在！');
            exit;
        }
        //验证密码
        if ($data['pass'] != md5($password)) {
            $this->error('密码不正确');
            exit;
        }


        $captcha=input("post.verify","");
        if(empty($captcha)){
            return json(['code'=>0,'data'=>'','msg'=>'验证码不能为空!']);
        }
        if(!captcha_check($captcha)) {
            return $this->error('验证失败');
        }
        //把用户信息添加到session
        session('login_admin',$data);

        $this->redirect('index/Index/index');
    }

    // 手机登录
    public function loginTel()
    {


        //接收用户名和密码

        $phone = $_POST['user_phone'];
        $password = $_POST['pass'];

        //验证

        $data = Db::name('index_login')->field('user_phone, pass,id')->where(array('user_phone' => $phone))->find();


        if (!$data) {
            $this->error('用户名不存在！');
            exit;
        }
        //验证密码
        if ($data['pass'] != md5($password)) {
            $this->error('密码不正确');
            exit;
        }


        $captcha=input("post.verify","");
        if(empty($captcha)){
            return json(['code'=>0,'data'=>'','msg'=>'验证码不能为空!']);
        }
        if(!captcha_check($captcha)) {
            return $this->error('验证失败');
        }
        //把用户信息添加到session
        session('login_tel',$data);

        $this->redirect('index/Index/index');
    }


    // 退出登录 并且清除session
    public function out()
    {
        Session::clear();
        $list = Db::name('index_navigation')->select();
        if ($list > 0) {
            return $this->success('退出成功', url('index/index/index'));
        } else {
            return $this->error('退出失败');
        }

    }
}